package translate;

import Base.ResourceTest;
import com.huawei.translate.api.TranslateApi;
import com.huawei.translate.model.MsAccessToken;
import com.huawei.translate.persistence.MsAccessTokenRepository;
import com.huawei.translate.provider.MSTranslateProvider;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

import static org.mockito.Mockito.when;

@RunWith(SpringRunner.class)
public class When_request_refresh_ms_access_token extends ResourceTest {

    @Autowired
    private MsAccessTokenRepository msAccessTokenRepository;

    @Autowired
    @Mock
    private MSTranslateProvider msTranslateProvider;

    @Autowired
    @InjectMocks
    private TranslateApi translateApi;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void should_refresh_ms_access_token() {
        String msAccessToken = "msAccessToken";
        when(msTranslateProvider.getAccessToken()).thenReturn(msAccessToken);
        ResponseEntity response = sendRefreshRequest();

        List<MsAccessToken> accessToken = msAccessTokenRepository.findAllByOrderByUpdatedAtDesc();

        Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
        Assert.assertEquals(msAccessToken, accessToken.get(0).getAccessToken());
    }

    @Test
    public void should_refresh_ms_access_token_when_request_again() {
        String msAccessToken = "msAccessToken";
        when(msTranslateProvider.getAccessToken()).thenReturn(msAccessToken);
        sendRefreshRequest();

        List<MsAccessToken> tokenBefore = msAccessTokenRepository.findAllByOrderByUpdatedAtDesc();

        Assert.assertEquals(1, tokenBefore.size());

        ResponseEntity response = sendRefreshRequest();

        List<MsAccessToken> tokenAfter = msAccessTokenRepository.findAllByOrderByUpdatedAtDesc();

        Assert.assertEquals(1, tokenAfter.size());

        Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
    }

    @After
    public void cleanup() {
        msAccessTokenRepository.deleteAll();
    }

    private ResponseEntity sendRefreshRequest() {
        return this.testRestTemplate.postForEntity("/api/translates/token", null, null);
    }
}
